package com.snapp.web.actions.access;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.jdom.Element;

import com.snapp.util.object.DBObject;
import com.snapp.web.SNAppAccess;
import com.snapp.web.SNAppAction;

public class CheckSession extends SNAppAction {

	public String execute(HttpServletRequest req) {
		
		DBObject acc = null;
		
		if (SNAppAccess.isValid(req)) {
			// retrieve access from session
			HttpSession sess = req.getSession();
			acc = (DBObject)sess.getAttribute("access");
			
			// set results and detail in logs
			setResults(RESULT_CODE_SUCCESS,"Access retrieved.");
			log("Access retrieved from session for "+acc.getBean().getPropertyString("fname") + " " + acc.getBean().getPropertyString("lname"));
			
			// get permissions map
			Map<String, String> pMap = (Map<String,String>)sess.getAttribute("permits");
			
			try {
				// get body element
				Element body = acc.getBean().toXML();
				
				// add permits
				Element perms = new Element("permits");
				
				Iterator<String> itr = pMap.keySet().iterator();
				while (itr.hasNext()) {
					String ky = itr.next();
					
					// add attribute to permissions
					perms.setAttribute(ky,pMap.get(ky));
					
				}
				// add permissions to return xml
				body.addContent(perms);
				
				// add function tree to body element
				//body.addContent(((Element)acc.getBean().getProperty("functions")).detach());
				
				// set the body element
				setBodyElement(body);
		
			} catch(Exception e) {
				setResults(RESULT_CODE_WARNING,"No session detected");
				log("Unknown error retrieving session.", e);
			}

		} else {
			setResults(RESULT_CODE_WARNING,"No session detected");
		}
		
		return super.execute(req);
		
	}

	/**
	 * Bypass the session check for invalid Logins.
	 * @param req
	 * @return
	 */
	public String bypass(HttpServletRequest req) {
		
		return super.execute(req);
	}
}
